package com.lcm.jnode.controller.api;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletInputStream;

import org.apache.log4j.Logger;

import com.gson.bean.Articles;
import com.gson.bean.InMessage;
import com.gson.bean.OutMessage;
import com.gson.inf.MessageProcessingHandler;
import com.gson.util.Tools;
import com.gson.util.XStreamFactory;
import com.jfinal.core.Controller;
import com.lcm.jnode.handler.WeChatMessageHandler;
import com.lcm.jnode.utils.ConfigUtil;
import com.thoughtworks.xstream.XStream;

/**
 * 微信开放平台api
 * @author L.cm
 * @date 2013-5-14 下午5:08:12
 * 参考自：<url>http://git.oschina.net/gson/wechat</url>
 */
public class WeChat extends Controller {

	private static final Logger log = Logger.getLogger(WeChat.class);
	
	public void index() throws IOException {
		if( "GET".equals(getRequest().getMethod()) ) {
			do_get();
		}else{
			do_post();
		}
	}
	
	public void do_get() {
		String signature = getPara("signature"); 	// 微信加密签名
		String timestamp = getPara("timestamp"); 	// 时间戳
		String nonce = getPara("nonce");		 	// 随机数
		String echostr = getPara("echostr");		// 随机字符串
		String token = ConfigUtil.get("token");		// token
		//验证
		if (Tools.checkSignature(token, signature, timestamp, nonce)) {
			renderText(echostr);
		}
	}
	
	public void do_post() throws IOException {
		getResponse().setCharacterEncoding("UTF-8");
		OutMessage oms = null;
		
		ServletInputStream in = getRequest().getInputStream();
		String xmlMsg = Tools.inputStream2String(in);
		log.error(xmlMsg);
		XStream xs = XStreamFactory.init(false);
		//转换微信post过来的xml内容
		xs.alias("xml", InMessage.class);
		InMessage msg = (InMessage) xs.fromXML(xmlMsg);
		// 微信Handler消息处理
		WeChatMessageHandler weChatHandler = new WeChatMessageHandler();
		//取得消息类型
		String type = msg.getMsgType();
		//针对不同类型消息进行处理
		if (type.equals(MessageProcessingHandler.MSG_TYPE_TEXT)) {
			oms = weChatHandler.textTypeMsg(msg);
		} else if (type.equals(MessageProcessingHandler.MSG_TYPE_LOCATION)) {
			oms = weChatHandler.locationTypeMsg(msg);
		} else if (type.equals(MessageProcessingHandler.MSG_TYPE_LINK)) {
			oms = weChatHandler.linkTypeMsg(msg);
		} else if (type.equals(MessageProcessingHandler.MSG_TYPE_IMAGE)) {
			oms = weChatHandler.imageTypeMsg(msg);
		} else if (type.equals(MessageProcessingHandler.MSG_TYPE_EVENT)) {
			oms = weChatHandler.eventTypeMsg(msg);
		} else if (type.equals(MessageProcessingHandler.MSG_TYPE_VOICE)) {
		    oms = weChatHandler.voiceTypeMsg(msg);
		} else {
		    oms = weChatHandler.textTypeMsg(msg);
		}
		//设置发送信息
		oms.setCreateTime(new Date().getTime());
		oms.setToUserName(msg.getFromUserName());
		oms.setFromUserName(msg.getToUserName());
		// 把发送发送对象转换为xml输出
		// outInit 对源码重写对Number类型的排除<![CDATA[]]>标签
		xs = XStreamFactory.outInit(true);
		xs.alias("xml", OutMessage.class);
		xs.alias("item", Articles.class);
		log.error(xs.toXML(oms));
		renderText(xs.toXML(oms), "text/xml");
	}
}
